<template>
  <el-dialog v-model="visible" :title="formDisabled? '查看':form.id ? '编辑' : '添加'" width="550px" @closed="onReset">
    <el-form :disabled="formDisabled" :model="form" label-width="100" ref="formRef" :rules="formRules">
      <el-form-item label="上级" prop="parentName">
        <el-input v-model="form.parentName" :disabled="true" placeholder="根目录" clearable />
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="form.menuType">
          <el-radio :label="1" :value="1" :disabled="!typeList.includes(1)">目录</el-radio>
          <el-radio :label="2" :value="2" :disabled="!typeList.includes(2)">菜单</el-radio>
          <el-radio :label="3" :value="3" :disabled="!typeList.includes(3)">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="名称" prop="menuName">
        <el-input v-model="form.menuName" placeholder="请输入菜单名称" clearable />
      </el-form-item>
      <el-form-item label="组件路径" prop="path" v-if="form.menuType !== 3">
        <el-input v-model="form.path" placeholder="请输入组件路径" clearable />
        <div class="text-neutral text-xs">如：`/system/menu`，路由路径</div>
      </el-form-item>
      <el-form-item label="显示排序" prop="orderNum">
        <el-input v-model="form.orderNum"  @input="validatePhoneNumber" placeholder="请输入菜单名称" clearable />
      </el-form-item>
      <el-form-item label="按钮类型" prop="btnType" v-if="form.menuType ==3">
        <el-radio-group v-model="form.btnType" class="w-full">
          <el-radio :label="1" :value="1">表头按钮</el-radio>
          <el-radio :label="2" :value="2">操作按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限标识" prop="perms" >
        <el-input v-model="form.perms" placeholder="请输入组件路径" clearable />
      </el-form-item>
      <el-form-item label="图标" prop="menuIcon" v-if="form.menuType !==3">
        <select-icon v-model="form.menuIcon" style="width: 100%" />
      </el-form-item>
      <el-form-item label="是否机构" prop="isInstitution">
        <el-radio-group v-model="form.isInstitution" class="w-full">
          <el-radio :label="1" :value="1">是</el-radio>
          <el-radio :label="0" :value="0">否</el-radio>
        </el-radio-group>
        <div class="text-neutral text-xs">“机构管理员”权限包括【菜单权限】和【角色权限】</div>
      </el-form-item>
      <el-form-item label="是否顾问" prop="isHealthDoctor">
        <el-radio-group v-model="form.isHealthDoctor" class="w-full">
          <el-radio :label="1" :value="1">是</el-radio>
          <el-radio :label="0" :value="0">否</el-radio>
        </el-radio-group>
        <div class="text-neutral text-xs">“健康顾问”权限仅包括【菜单权限】，不受【角色权限】影响</div>
      </el-form-item>
      <el-form-item label="状态" prop="visible">
        <el-radio-group v-model="form.visible" class="w-full">
          <el-radio :label="0" :value="0">显示</el-radio>
          <el-radio :label="1" :value="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button v-if="formDisabled" @click="oncancel">关闭</el-button>
        <el-button v-if="!formDisabled" @click="oncancel">取消</el-button>
        <el-button v-if="!formDisabled" type="primary" @click="onsubmit(formRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue';
import type { IMenuItem } from '@/api/auth/type';
import { formRules } from '../helpers/rule';
import type { FormInstance} from 'element-plus';
import { editMenu, addMenu } from "@/api/system/menu";
import { getMenuList } from '@/api/auth';
import { storage } from '@/utils/storage';
interface Props {
  treeData: IMenuItem[];
}

const props = defineProps<Props>();
const visible = ref(false);
const formRef =ref<FormInstance>();
const typeList = ref<number[]>([])
const form = reactive({
    id: 0,
    parentId: 0,
    parentName: '',
    menuName: "",
    orderNum: 0,
    menuType: 1,
    perms: "",
    btnType: 1,
    path: "",
    menuIcon: null,
    isInstitution: 0,
    isHealthDoctor: 0,
    children: [],
    visible: 0,
});
const oldForm = {
    id: 0,
    parentId: 0,
    parentName: '',
    menuName: "",
    orderNum: 0,
    menuType: 1,
    perms: "",
    btnType: 1,
    path: "",
    menuIcon: null,
    isInstitution: 0,
    isHealthDoctor: 0,
    children: [],
    visible: 0,
}

const validatePhoneNumber = (event:any) =>{
  // 限制只能输入数字
  form.orderNum = event.replace(/\D/g, '');
}
const dialogType = ref()
const formDisabled = ref(false) 
const init = async (data?: IMenuItem, type?: String) => {
  visible.value = true;
  dialogType.value = type
  if (data) {
    await nextTick();
    Object.assign(form, data);
  }
  if(type === 'tableAdd') {
    typeList.value = [1,2]
  }
  if(type=== 'add') {
    if(data.menuType == 1) {
      typeList.value = [2]
      form.menuType = 2
    }
    if(data.menuType == 2) {
      typeList.value = [3]
      form.menuType = 3
    }
  }
  if(type==='edit') {
    typeList.value = []
  }
  if(type === 'check') {
    formDisabled.value = true
  } else{
    formDisabled.value = false
  }
};
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible']);
const onsubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let Url = dialogType.value == 'edit' ? editMenu : addMenu;
      let res: any = await Url(form);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        
        const menuList = await getMenuList({});
        console.log(menuList.data);
        const menus = JSON.stringify(menuList.data)
        storage.set('menu', menus);
        window.location.reload()
        emit("updateList", false);
      } else {
        ElMessage.error(res.message)
      }
      visible.value = false
      onReset()

    } else {
      console.log('保存失败', fields)
    }
  })
}

const oncancel = () => {
  visible.value = false
  onReset()
}
const onReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  Object.assign(form, oldForm);
};

defineExpose({ init });
</script>

<style lang="scss" scoped></style>
